package com.glasgowcompsoc.musicplayer.player;

import java.io.IOException;
import java.io.InputStream;

import de.vdheide.mp3.FrameDamagedException;
import de.vdheide.mp3.ID3v2;
import de.vdheide.mp3.ID3v2Exception;
import de.vdheide.mp3.TextFrameEncoding;

import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;

/**
 * Wrapper for mp3 files which provides basic metadata
 * and utility functions for media playback.
 */
public class Song {
	private String artist;
	private String title;
	private String album;
	private MediaPlayer mediaPlayer;
	
	/**
	 * Create a new Song instance from an asset file
	 * descriptor. Searches for ID3 metadata automatically.
	 * Recommend populating playlists in a separate thread
	 * because of IO overheads.
	 *  
	 * @param afd
	 * 
	 * @throws IOException
	 */
	public Song(AssetFileDescriptor afd) throws IOException {
		super();
		
		/* 1. Attempt to read ID3v2 tags from file. */
		InputStream is = afd.createInputStream();
		
		ID3v2 tags = null;
		
		try {
			tags = new ID3v2(is);
		} catch (ID3v2Exception e) {
			e.printStackTrace();
			
			artist = "Unknown Artist";
			title = "Unknown";
			album = "Unknown Album";
			
			return;
		}
		
		/* 2. Read relevant metadata from ID3 frames. */
		
		try {
			artist = TextFrameEncoding.read(tags, "TPE1").getTextContent();
		} catch (FrameDamagedException e) {
			artist = "Unknown Artist";
		}
		
		try {
			title = TextFrameEncoding.read(tags, "TIT2").getTextContent();
		} catch (FrameDamagedException e) {
			title = "Unknown";
		}
		
		try {
			album = TextFrameEncoding.read(tags, "TALB").getTextContent();
		} catch (FrameDamagedException e) {
			album = "Unknown Album";
		}
		
		mediaPlayer = new MediaPlayer();
		mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
		mediaPlayer.prepare();
	}
	
	/**
	 * @return Arist name, taken from song's ID3 metadata.
	 */
	public String getArtist() {
		return artist;
	}
	
	/**
	 * @return Song title, taken from song's ID3 metadata.
	 */
	public String getTitle() {
		return title;
	}
	
	/**
	 * @return Album name, taken from song's ID3 metadata.
	 */
	public String getAlbum() {
		return album;
	}
	
	/**
	 * Creates a MediaPlayer instance which is ready to start
	 * playing this song.
	 * 
	 * @return Prepared instance of MediaPlayer, ready to start playing
	 * 
	 * @throws IllegalArgumentException
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	public MediaPlayer getMediaPlayer() throws IllegalArgumentException, IllegalStateException, IOException {
		mediaPlayer.seekTo(0);
		
		return mediaPlayer;
	}
}
